package com.changgou.system.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.system.pojo.Admin;
import com.changgou.system.service.AdminService;
import com.changgou.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @GetMapping
    public Result<List<Admin>> findList() {
        List<Admin> adminList = adminService.findList();
        return new Result<>(true, StatusCode.OK, "查询成功", adminList);
    }

    @GetMapping("/{id}")
    public Result<Admin> findById(@PathVariable("id") Integer id) {
        Admin admin = adminService.findById(id);
        return new Result<>(true, StatusCode.OK, "查询成功", admin);
    }

    @PostMapping
    public Result<Admin> add(@RequestBody Admin admin) {
        adminService.add(admin);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @PutMapping("/{id}")
    public Result<Admin> update(@RequestBody Admin admin,@PathVariable Integer id) {
        admin.setId(id);
        adminService.update(admin);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @DeleteMapping("/{id}")
    public Result<Admin> delById(@PathVariable("id") Integer id) {
        adminService.delById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        boolean result = adminService.login(admin);
        if (result) {
            HashMap<String, String> hashMap = new HashMap();
            hashMap.put("username", admin.getLoginName());
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), admin.getLoginName(), null);
            hashMap.put("token", token);
            return new Result(true, StatusCode.OK,"登录成功",hashMap);
        } else {
            return new Result(false, StatusCode.ERROR,"登录失败");
        }
    }
}
